<?php

namespace App\Http\Middleware;

use App\Models\MemberBindAdmin;

use Admin;

use Closure;

class MemberBindAdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $type = 'activity')
    {
        try {
            // 验证管理员操作权限
            $member =  \Auth::guard('member')->user(); //当前管理员

            $member_bind = MemberBindAdmin::where('member_id', $member->member_id)->first();

            if (!$member_bind)
            {
                return response()->json(['code' => 200200, 'msg' => '您未绑定为操作员', 'data'=> null]);
            }

            $users_model = config('admin.database.users_model');

            $admin = $users_model::where('id', $member_bind->admin_id)->first();
            if (!$admin)
            {
                return response()->json(['code' => 200200, 'msg' => '您绑定的管理员不存在', 'data'=> null]);
            }

            if (!$admin->can($type))
            {
                return response()->json(['code' => 200200, 'msg' => '您无此操作权限', 'data'=> null]);
            }

        } catch (\Exception $exception) {
            return response()->json(['code' => 100003, 'msg' => $exception->getMessage(), 'data'=> null]);
        }

        return $next($request);
    }
}
